import store from '@/store';
import base from "@/config/baseUrl";

// 获取链接参数
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

// 微信公众号一键登录
export const h5Login = (callback) => {
	var local = encodeURIComponent(window.location.href);
	var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + base.publicAppId + "&redirect_uri=" +
		local + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
	var code = getUrlParam("code");
	if (!code) {
		window.location = url;
	} else {
		var httpData = {
			code: code
		}
		if (store.state.distributionId) {
			httpData.distributionId = store.state.distributionId;
		}
		uni.$u.http.post('/openapi/weiXinLogin', httpData).then((res) => {
			// 存储token
			uni.setStorageSync('userToken', res);
			// 获取用户信息
			getUserInfo();
			callback && callback(res)
		})
	}
}

// 浏览器判断是否微信
export const isWechat = () => {
	let ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		//console.log('是微信客户端')  
		return true;
	} else {
		//console.log('不是微信客户端')  
		return false;
	}
};

// 获取用户信息
export const getUserInfo = (callback, load = true) => {
	uni.$u.http.get("/approve/members/getMemberInfo", {
		custom: {
			load
		}
	}).then((res) => {
		let userInfo = {
			...res,
			token: true, //token用于判断是否登录
		}
		if (!res.telPhone || res.telPhone == "" || res.telPhone == null) {
			store.commit('setBindPhonePopupShow', true);
		}
		store.commit('setUserInfo', userInfo)
		callback && callback(res);
	});
}
